package com.xiaopeng.common.httpResult.advice;


import com.xiaopeng.common.exception.BusinessException;
import com.xiaopeng.common.httpResult.enums.HttpResultCodeEnum;
import com.xiaopeng.common.httpResult.model.HttpResult;
import com.xiaopeng.common.httpResult.util.ExceptionLogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * @author xiaopeng
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerAdvice {


    /**
     * 处理未捕获的Exception
     *
     * @param e 异常
     * @return 统一响应体
     */
    @ExceptionHandler(Exception.class)
    public HttpResult<Void> handleException(Exception e) {
        ExceptionLogUtil.logErr(e);
        return HttpResult.fail(HttpResultCodeEnum.FAIL.getCode(), HttpResultCodeEnum.FAIL.getMessage());
    }

    /**
     * 处理未捕获的RuntimeException
     *
     * @param e 运行时异常
     * @return 统一响应体
     */
    @ExceptionHandler(RuntimeException.class)
    public HttpResult<Void> handleRuntimeException(RuntimeException e) {
        ExceptionLogUtil.logErr(e);
        return HttpResult.fail(HttpResultCodeEnum.FAIL.getCode(), HttpResultCodeEnum.FAIL.getMessage());
    }

    /**
     * 处理业务异常BaseException
     *
     * @param e 业务异常
     * @return 统一响应体
     */
    @ExceptionHandler(BusinessException.class)
    public HttpResult<Void> handleBaseException(BusinessException e) {
        ExceptionLogUtil.logErr(e);
        return HttpResult.fail(e.getCode(), e.getMessage());
    }


    /**
     * 处理HTTP消息不可读异常
     *
     * @param e 异常
     * @return 统一响应体
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpResult<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        ExceptionLogUtil.logErr(e);
        return HttpResult.fail(HttpResultCodeEnum.REQUEST_PARAM_INVALID.getCode(),
            HttpResultCodeEnum.REQUEST_PARAM_INVALID.getMessage());
    }

}
